<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拖拽回放</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        .box{
            width: 100px;
            height: 100px;
            background: red;
            cursor: move;
            position: absolute;
        }
        button{
            position: fixed;
            right: 0;
            top: 0;
            padding: 5px 20px;
            font-size: 20px;
            user-select: none;
        }
    </style>
</head>
<body>
    <button>回放</button>
    <div class="box"></div>

    <script>
        // 获取元素
        var box = document.querySelector('.box');
        var btn = document.querySelector('button');
        // 创建空数组，存储坐标
        var arr = [];

        // 点下
        box.onmousedown = function(e){
            // 光标到盒子的左上边距
            var ox = e.offsetX;
            var oy = e.offsetY;

            // 移动
            document.onmousemove = function(e){
                // 设置盒子到可视窗口的左上边距
                var boxLeft = e.clientX - ox;
                var boxTop = e.clientY - oy;

                // 禁止超出
                if(boxLeft < 0){
                    boxLeft = 0;
                }
                if(boxLeft > window.innerWidth - box.offsetWidth){
                    boxLeft = window.innerWidth - box.offsetWidth
                }

                if(boxTop < 0){
                    boxTop = 0;
                }
                if(boxTop > window.innerHeight - box.offsetHeight){
                    boxTop = window.innerHeight - box.offsetHeight
                }

                // 记录坐标
                var coordinates = [];
                coordinates.push(boxLeft,boxTop);
                arr.push(coordinates);
                
                // 设置边距
                box.style.left = boxLeft + 'px';
                box.style.top = boxTop + 'px';
            }
        }

        // 停止移动
        document.onmouseup = function(){
            document.onmousemove = null;
        }

        // 回放
        btn.onclick = function(){
            // 从第一个坐标开始回放
            var i = 0;
            var time = setInterval(function(){
                box.style.left = arr[i][0] + "px";
                box.style.top =  arr[i][1] + "px";
                i++;
                // 数据读取完毕，清空定时器
                if(i>arr.length-1){
                    clearInterval(time);
                    // 清空数组
                    arr.length = 0;
                }
            },10);
        }
    </script>
</body>
</html>